/**
 * 面试列表页
 */
import React, { useCallback, useRef } from 'react';
import { withRouter, Link } from 'umi';
import {
    Form,
    Select,
    Row,
    Col,
    Card,
    Tag,
    Spin,
    message,
    Avatar,
    ConfigProvider,
    Modal,
    List,
    Divider,
    Collapse
} from 'antd';
import { debounce } from 'lodash';

import Pre from '@/components/Pre';
import { useRequest, defaultFormatResult } from '@/hooks';
import { PageContainer, IM } from '@/molecules';
import pageTabUtil from '@/utils/pageTabUtil';
import cn from 'classnames';
import { TitleControl, Evaluation, FileShowView, PreviewModal } from '../components/index';
import { AssessFrom, DetailQuestion } from '../containers';
import styles from './Detail.less';
import { getFileType } from '../../EntryManage/utils';
import {
    getTalentMessage,
    getArranges,
    getConclusion,
    submitConclusion,
    createImGroup,
    getConclusionSubmitStatus
} from '../service';

import mapData from './statusMap';

import { useBeforeConclusion } from './hooks';
import { AbsentList, RecommendTip } from './Containers';

const { colorObj, textObj } = mapData;
const { Option } = Select;
let title = '面试详情';
const Detail = ({ location, form }) => {
    const { query, pathname } = location;
    const previewRef = useRef();
    const { candidateId = 539, arrangeId = '' } = query; // create创建 edit编辑
    // const dict = [];
    const isConclusion = pathname === '/office/personnelManagement/recruitment/interview/conclusion';
    if (isConclusion) {
        title = '面试总结';
    }

    const { tabModalContent } = useBeforeConclusion(arrangeId, isConclusion);

    const [pageLoading, setPageLoading] = React.useState(false);
    const [round, setRound] = React.useState(arrangeId);
    const [interviewer, setInterviewer] = React.useState([]);
    const [viewer, setViewer] = React.useState('');
    const [changeQueryStatus, setChangeQueryStatus] = React.useState(true);
    const tableRef = React.useRef();
    const payload = {
        candidateId
    };
    if (round !== '') {
        payload.arrangeId = round;
    }
    if (viewer !== '') {
        payload.employeeCode = viewer;
    }
    const settings = { checkIs: 0, starIs: 0, scoreIs: 1, textIs: 0, passScoreIs: 0 };
    const { data: talentData = {}, loading: talentLoading } = useRequest(() => getTalentMessage(candidateId), {
        ...defaultFormatResult
    });
    const { data: arrangesData = [] } = useRequest(() => getArranges(candidateId), {
        ...defaultFormatResult
    });
    const { data: conclusionData = [], loading: conclusionLoading, run: runConclusion } = useRequest(
        () => getConclusion(payload),
        {
            manual: isConclusion && changeQueryStatus,
            refreshDeps: [round, viewer],
            ...defaultFormatResult
        }
    );
    const { loading: imLoading } = useRequest(
        () =>
            createImGroup({
                arrangeId
            }),
        {
            ready: isConclusion,
            ...defaultFormatResult,
            onSuccess() {
                setChangeQueryStatus(false);
                runConclusion();
            }
        }
    );
    const { dutyName, rankValue, organizationName, talentName, recruitTalentMatcherId = '' } = talentData;

    // 预览文件
    const handlePreview = source => {
        const { id, url, name } = source;
        const fileType = getFileType(name);
        previewRef.current.open({
            type: fileType,
            title: id,
            origin: url,
            encode: fileType === 'office',
            originName: name
        });
    };

    const getTitle = (value, resultList) => {
        const currentResult = resultList.find(item => item.arrangeId === value.id);
        return (
            <span className={styles.title} style={{ display: 'flex' }}>
                {value?.interviewRoundName}
                <Tag color={colorObj[value?.interviewStatus]} style={{ marginLeft: '10PX' }}>
                    {textObj[colorObj[value?.interviewStatus]]}
                </Tag>
                <RecommendTip result={currentResult} />
            </span>
        );
    };
    // 复杂的数据转换
    const processItem = useCallback((resultItems, oldItems) => {
        // eslint-disable-next-line no-plusplus
        for (let i = 0; i < oldItems.length; i++) {
            const item = oldItems[i];
            if (!resultItems[`item_${item.itemId}`]) {
                resultItems[`item_${item.itemId}`] = {};
                resultItems[`item_${item.itemId}`].eval_names = [];
            }
            resultItems[`item_${item.itemId}`].itemId = item.itemId;
            resultItems[`item_${item.itemId}`].itemName = item.itemName;
            resultItems[`item_${item.itemId}`].passScore = item.passScore;
            resultItems[`item_${item.itemId}`].itemDesc = item.itemDesc;
            resultItems[`item_${item.itemId}`].itemEvaluateReason = item.itemEvaluateReason;
            // 不显示还未填写面试记录的面试官 进入面试详情统计
            if (item.itemEvaluateScore !== undefined) {
                resultItems[`item_${item.itemId}`][`${item.evaluateEmployeeName}`] = item.itemEvaluateScore;
                resultItems[`item_${item.itemId}`].eval_names.push(item.evaluateEmployeeName);
            }
            // resultItems[`item_${item.itemId}`][`${item.createUser}_reason`] = item.itemEvaluateReason;
        }
    }, []);
    const processForm = React.useCallback((data = []) => {
        const result = {};
        // eslint-disable-next-line no-plusplus
        for (let i = 0; i < data.length; i++) {
            const forms = result[`form_${data[i].formId}`];
            if (!forms) {
                const newForm = {};
                newForm.formId = data[i].formId;
                newForm.formName = data[i].formName;
                newForm.arrangeId = data[i].arrangeId;
                newForm.formItems = {};
                result[`form_${data[i].formId}`] = newForm;
            }
            processItem(result[`form_${data[i].formId}`].formItems, data[i].formItems);
            // processItem(result["form_"+data[i].formId]);
        }
        const res = Object.values(result).map(x => ({
            arrangeId: x.arrangeId,
            formId: x.formId,
            formName: x.formName,
            formItems: Object.values(x.formItems).filter(_ => _.eval_names.length > 0) // 过滤不显示面试官未填写的评估项目
        }));
        return res;
    }, []);
    // 某项评估表只有一个面试官 且该面试官未填写面试记录 则在面试详情页面不展示该评估表
    const getEval = data => {
        let res = [];
        data.forEach(x => {
            res = [...x.eval_names, ...res];
        });
        if (res.length > 0) {
            return true;
        }
        return false;
    };
    const handleChangeRound = value => {
        setRound(value);
        setViewer('');
    };

    const handleChangeViewer = value => {
        setViewer(value);
    };
    const onSubmitConclusion = async values => {
        try {
            const { resultType, resultContent, recommendRecruitId, needBackgroundFlag } = values;
            const res = await submitConclusion({
                arrangeId,
                resultType,
                resultContent,
                candidateId,
                recommendRecruitId,
                needBackgroundFlag
                // backgroundNum
            });
            if (res.code === 10000) {
                pageTabUtil.goBack();
            } else if (res.code === 11000) {
                message.error('请先前往【招聘设置-通知模板】配置通知发件邮箱，以便发送背调通知');
            } else {
                message.error(res.msg);
            }
        } catch (e) {
            console.log(e);
        }
    };
    /**
     * 提交面试总结
     */
    const onInterviewSubmit = debounce(() => {
        form.validateFields(async (err, values) => {
            const needBackgroundFlag = Number(values.needBackgroundFlag); // 是否需要背调
            // const backgroundNum = values?.backgroundNum !== undefined ? values.backgroundNum : null; // 是否需要背调
            const tempValues = {
                ...values,
                needBackgroundFlag
                // backgroundNum
            };
            console.log(tempValues);
            if (!err) {
                try {
                    setPageLoading(true);
                    const { code, data } = await getConclusionSubmitStatus(arrangeId);
                    setPageLoading(false);
                    if (code === 10000) {
                        if (data) {
                            onSubmitConclusion(tempValues);
                            return;
                        }
                        Modal.confirm({
                            title: '提示',
                            content: '还有面试官未提交面试记录，是否发起面试总结？',
                            onOk: async () => {
                                onSubmitConclusion(tempValues);
                            }
                        });
                    }
                } catch (e) {
                    setPageLoading(false);
                }
            }
        });
    }, 400);

    React.useEffect(() => {
        let total;
        if (round) {
            total = arrangesData.filter(item => item?.arrangeDetailVO?.id === Number(round))[0]?.arrangeDetailVO
                ?.interviewEmployees;
        } else {
            total = [];
            arrangesData.forEach(item => {
                total.push(...item?.arrangeDetailVO?.interviewEmployees);
            });
        }
        const map = {};
        // 简单排重一下
        const uniqueTotal = (total ?? []).filter(item => {
            const notExist = !map[item.employeeCode];
            map[item.employeeCode] = true;
            return notExist;
        });
        setInterviewer(uniqueTotal);
        if (arrangeId) setRound(Number(arrangeId));
    }, [round, JSON.stringify(arrangesData), arrangeId]);

    const defaultRecommendValue = conclusionData.find(item => item.arrangeId === Number(arrangeId))
        ?.recommendEvaluateResultVO?.recommendRecruitId;

    const renderQuestionList = item => {
        const dataSource = JSON.parse(item?.interviewArranges?.homework?.topicFileUrl || '[]');
        if (!dataSource.length) return null;

        return (
            <List
                split={false}
                itemLayout="horizontal"
                // eslint-disable-next-line max-len
                dataSource={dataSource.map(item5 => ({
                    uid: item5.id,
                    name: item5.name,
                    status: 'done',
                    url: item5.url,
                    response: item5.url
                }))}
                renderItem={item6 => (
                    <List.Item key={item6.uid}>
                        <FileShowView
                            handlePreview={handlePreview}
                            item={item6}
                            showPreview
                            showDownLoad
                        ></FileShowView>
                    </List.Item>
                )}
            />
        );
    };

    return (
        <PageContainer>
            <Spin spinning={pageLoading}>
                <div className={styles.title}>{title}</div>
                <ConfigProvider getPopupContainer={trigger => tableRef.current || trigger}>
                    <Form layout="inline" style={{ display: isConclusion ? 'none' : 'block' }}>
                        <Form.Item label="面试轮次">
                            <Select
                                placeholder="请选择面试轮次"
                                defaultValue=""
                                value={round}
                                style={{ width: '180px' }}
                                onChange={handleChangeRound}
                            >
                                <Option value="">全部</Option>
                                {arrangesData
                                    .filter(f => f?.arrangeDetailVO?.interviewStatus !== 7)
                                    .map(item => (
                                        <Option
                                            mode="tags"
                                            value={item?.arrangeDetailVO?.id}
                                            key={item?.arrangeDetailVO?.id}
                                        >
                                            {item?.arrangeDetailVO?.interviewRoundName}
                                        </Option>
                                    ))}
                            </Select>
                        </Form.Item>
                        <Form.Item label="面试官" styles={{ marginLeft: '20px' }}>
                            <Select
                                placeholder="请选择面试官"
                                defaultValue=""
                                value={viewer}
                                style={{ width: '180px' }}
                                onChange={handleChangeViewer}
                            >
                                <Option value="">全部</Option>
                                {interviewer.map(item => (
                                    <Option value={item.employeeCode} key={item.employeeCode}>
                                        {`${item.employeeName} ${item.positionName}/${item.rankValue}`}
                                    </Option>
                                ))}
                            </Select>
                        </Form.Item>
                    </Form>
                </ConfigProvider>
                <div className={styles.lineB}></div>
                <Spin spinning={talentLoading}>
                    <div className={styles.interMess}>
                        <Row gutter={[100, 15]}>
                            <Col span={12}>
                                <span className={styles.labels}>姓名：</span>
                                <Link
                                    to={{
                                        pathname: '/office/personnelManagement/recruitment/resume/detail',
                                        query: { id: recruitTalentMatcherId }
                                    }}
                                >
                                    <span className={styles.values}>{talentName}</span>
                                </Link>
                            </Col>
                            <Col span={12}>
                                <span className={styles.labels}>应聘岗位：</span>
                                <span className={styles.values}>{dutyName}</span>
                            </Col>
                            <Col span={12}>
                                <span className={styles.labels}>需求部门：</span>
                                <span className={styles.values}>{organizationName}</span>
                            </Col>
                            <Col span={12}>
                                <span className={styles.labels}>职级：</span>
                                <span className={styles.values}>{rankValue}</span>
                            </Col>
                        </Row>
                    </div>
                </Spin>
                <div className={styles.lineT}></div>
                <Spin spinning={conclusionLoading || imLoading}>
                    <TitleControl title="综合评价">
                        <div className={styles.interviewTotalEvaluateResults}>
                            {conclusionData.map(item => (
                                <Collapse
                                    defaultActiveKey="0"
                                    expandIconPosition="right"
                                    style={{ width: 723, marginBottom: 8 }}
                                >
                                    <Collapse.Panel
                                        key="0"
                                        header={getTitle(item.interviewArranges, item.interviewArrangeResults)}
                                    >
                                        <>
                                            {item?.interviewArranges?.interviewStatus !== 3 && (
                                                <>
                                                    <div>面试总结：</div>
                                                    <div>
                                                        <div className={styles.mess}>
                                                            <div className={styles.mLeft}>
                                                                <Avatar
                                                                    icon="user"
                                                                    src={
                                                                        item?.interviewArrangeResults[0]?.employeeAvatar
                                                                    }
                                                                    size={24}
                                                                    style={{ flex: '0 0 80px' }}
                                                                />
                                                            </div>
                                                            <div className={styles.mRight}>
                                                                <Row gutter={0}>
                                                                    <Col>
                                                                        <span className={styles.name}>
                                                                            {
                                                                                item?.interviewArrangeResults[0]
                                                                                    ?.resultEmployeeName
                                                                            }
                                                                        </span>
                                                                    </Col>
                                                                </Row>
                                                                <div className={styles.empty}></div>
                                                                <Row gutter={24}>
                                                                    <Col>
                                                                        <span className={styles.cont}>
                                                                            <Pre>
                                                                                {
                                                                                    item?.interviewArrangeResults[0]
                                                                                        ?.resultContent
                                                                                }
                                                                            </Pre>
                                                                        </span>
                                                                    </Col>
                                                                </Row>
                                                            </div>
                                                        </div>
                                                    </div>
                                                </>
                                            )}
                                            {item?.interviewArranges?.homework?.id && (
                                                <>
                                                    <div>面试题目：</div>
                                                    <div className={styles.topicInfo}>
                                                        {item?.interviewArranges?.homework?.topicInfo}
                                                    </div>

                                                    {item?.interviewArranges?.homework?.topicFileUrl && (
                                                        <div className={styles.fileInfo}>
                                                            {renderQuestionList(item)}
                                                        </div>
                                                    )}

                                                    <div>
                                                        <Divider></Divider>
                                                        <div>面试作业：</div>
                                                        {item?.interviewArranges?.homework?.answerFileUrl && (
                                                            <div className={styles.fileInfo}>
                                                                <List
                                                                    split={false}
                                                                    itemLayout="horizontal"
                                                                    dataSource={JSON.parse(
                                                                        item?.interviewArranges?.homework?.answerFileUrl
                                                                    ).map(item7 => ({
                                                                        uid: item7.id,
                                                                        name: item7.name,
                                                                        status: 'done',
                                                                        url: item7.url,
                                                                        response: item7.url
                                                                    }))}
                                                                    renderItem={item8 => (
                                                                        <List.Item key={item8.uid}>
                                                                            <FileShowView
                                                                                handlePreview={handlePreview}
                                                                                item={item8}
                                                                                showPreview
                                                                                showDownLoad
                                                                            ></FileShowView>
                                                                        </List.Item>
                                                                    )}
                                                                />
                                                            </div>
                                                        )}
                                                    </div>
                                                </>
                                            )}
                                            {!item?.interviewArranges?.homework?.id && (
                                                <DetailQuestion
                                                    dataSource={{
                                                        interviewEvaluateResults: item.interviewEvaluateResults,
                                                        interviewArranges: item.interviewArranges
                                                    }}
                                                />
                                            )}
                                            {!!item?.absentInterviews?.length && (
                                                <AbsentList dataSource={item?.absentInterviews} />
                                            )}
                                        </>
                                    </Collapse.Panel>
                                </Collapse>
                            ))}
                        </div>
                    </TitleControl>
                    {conclusionData.filter(item => item?.interviewArranges?.interviewWay !== 5).length > 0 && (
                        <>
                            <TitleControl title="面试问题">
                                {conclusionData.map(item =>
                                    item?.interviewQuestions.map((x, index) => (
                                        <Card
                                            title={
                                                <div style={{ lineHeight: '24px' }}>
                                                    {`${index + 1}、`}
                                                    <span style={{ wordBreak: 'break-all' }}>{`${x.question}`}</span>
                                                    <span
                                                        style={{
                                                            display: 'inline-flex',
                                                            color: 'rgba(0,0,0,0.15)',
                                                            fontSize: 14
                                                        }}
                                                    >
                                                        <i
                                                            className={cn(
                                                                'iconfont',
                                                                'iconcountpeople_o',
                                                                styles.createUserIcon
                                                            )}
                                                        />
                                                        <span style={{ color: 'rgba(0,0,0,0.65)', fontSize: 14 }}>
                                                            {x?.createUserName}
                                                        </span>
                                                    </span>
                                                </div>
                                            }
                                            headStyle={{ background: '#fafafa' }}
                                            style={{ marginBottom: '10px', width: '725px' }}
                                            className={styles.questionCard}
                                        >
                                            <DetailQuestion
                                                type="noState"
                                                dataSource={{
                                                    ...x,
                                                    timeInfo: item?.interviewArranges?.recordTimeInfo
                                                        ? JSON.parse(item?.interviewArranges?.recordTimeInfo)
                                                        : {},
                                                    recordUrl: item?.interviewArranges?.recordUrl
                                                }}
                                            />
                                        </Card>
                                    ))
                                )}
                            </TitleControl>

                            <TitleControl title="能力评估">
                                {conclusionData.map(
                                    item =>
                                        item?.evaluateFormInsts.length > 0 &&
                                        processForm(item?.evaluateFormInsts).map(
                                            x =>
                                                getEval(x.formItems) && (
                                                    <AssessFrom
                                                        settings={settings}
                                                        value={x}
                                                        detailShow
                                                        tableTitle={item?.interviewArranges?.interviewRoundName}
                                                        style={{ width: '725px' }}
                                                    />
                                                )
                                        )
                                )}
                                {/* {processForm(conclusionData?.evaluateFormInsts).map(item => (
                        <AssessFrom settings={settings} value={item} detailShow style={{ width: '725px' }} />
                    ))} */}
                            </TitleControl>
                        </>
                    )}

                    <TitleControl title="总结记录">
                        {/* 面试总结(皆可展示)/面试详情(状态为4=通过 5=淘汰 6=需复试可展示) */}
                        <div className={styles.conclusionImWrap}>
                            {conclusionData
                                .map(item => ({
                                    id: item?.interviewArranges?.imGroupId,
                                    title: item?.interviewArranges?.interviewRoundName,
                                    isEdit: isConclusion && item?.arrangeId.toString() === arrangeId.toString(),
                                    status: item?.interviewArranges?.interviewStatus
                                }))
                                .map(item => {
                                    if ((item.id && [4, 5, 6].includes(item.status)) || (item.id && isConclusion)) {
                                        return (
                                            <>
                                                <div className={styles.conclusionRoundTitle}>{item.title}</div>
                                                {item.isEdit && (
                                                    <div className={styles.conclusionImTip}>
                                                        已发起 IM
                                                        讨论，系统自动为招聘发起人、负责人、本轮面试官创建讨论群
                                                    </div>
                                                )}
                                                <IM groupId={item.id} readOnly={!item.isEdit} />
                                            </>
                                        );
                                    }
                                    return null;
                                })}
                        </div>
                    </TitleControl>
                    {pathname === '/office/personnelManagement/recruitment/interview/conclusion' ? (
                        <TitleControl title="综合评价" showButton={false}>
                            <Evaluation
                                isLastStep
                                form={form}
                                onSubmit={onInterviewSubmit}
                                style={{ width: '500px' }}
                                resumeId={talentData?.recruitTalentMatcherId}
                                defaultRecommendValue={defaultRecommendValue}
                            />
                        </TitleControl>
                    ) : null}
                </Spin>
                <PreviewModal title ref={previewRef} height="650px" />
                {tabModalContent}
            </Spin>
        </PageContainer>
    );
};

export default Form.create()(withRouter(Detail));
